package bean.managed;

import entity.CompletedGoodsEntity;
import bean.managed.util.JsfUtil;
import bean.managed.util.PaginationHelper;
import bean.session.CompletedGoodsEntityFacade;

import entity.BatchEntity;
import entity.BomRawMaterialWeightEntity;
import entity.CompletedGoodsLocationEntity;
import entity.LocationQuantityEntity;
import entity.OutboundCompletedGoodsEntity;
import entity.PickingOrderEntity;
import entity.PlannedReserveEntity;
import entity.ProductQuantityPriceEntity;
import entity.RawMaterialEntity;
import entity.ReservationEntity;
import entity.SalesOrderEntity;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.application.ViewHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.faces.validator.ValidatorException;
import managedbean.AbstractBacking;
import org.primefaces.event.FlowEvent;
import org.primefaces.model.DualListModel;

@ManagedBean(name = "completedGoodsEntityController")
@SessionScoped
public class CompletedGoodsEntityController extends AbstractBacking implements Serializable {
    
    private CompletedGoodsEntity current;
    private DataModel items = null;
    private DataModel expiringBatchesInLocation = null;
    private BatchEntity batchToRemove = null;
    //private List<BatchEntity> expiringBatches = new ArrayList<BatchEntity>();
    @EJB
    private bean.session.CompletedGoodsEntityFacade ejbFacade;
    @EJB
    private bean.session.RawMaterialEntityFacade materialFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private int totalCGCapacity;
    private int totalCGUsage;
    private static Logger logger = Logger.getLogger(CompletedGoodsEntityController.class.getName());    
    private ArrayList<BomRawMaterialWeightEntity> bomMaterialList = new ArrayList<BomRawMaterialWeightEntity>();    
    private ArrayList<CompletedGoodsEntity> completedGoodsList = new ArrayList<CompletedGoodsEntity>();
    @ManagedProperty(value = "#{completedGoodsLocationEntityController}")
    CompletedGoodsLocationEntityController completedGoodsLocationEntityController;
    @ManagedProperty(value = "#{locationQuantityEntityController}")
    LocationQuantityEntityController locationQuantityEntityController;
    @ManagedProperty(value = "#{inventoryEntityController}")
    InventoryEntityController inventoryEntityController;
    @ManagedProperty(value = "#{batchEntityController}")
    BatchEntityController batchEntityController;
    @ManagedProperty(value = "#{disposalEntityController}")
    DisposalEntityController disposalEntityController;
    @ManagedProperty(value = "#{salesOrderEntityController}")
    SalesOrderEntityController salesOrderEntityController;
    @ManagedProperty(value = "#{outboundCompletedGoodsEntityController}")
    OutboundCompletedGoodsEntityController outboundCompletedGoodsEntityController;
    //@ManagedProperty(value = "#{pickingOrderEntityController}")
    PickingOrderEntityController pickingOrderEntityController;
    ReservationEntityController reservationEntityController;
    private CompletedGoodsLocationEntity viewLocation;
    private CompletedGoodsLocationEntity expiringCGInLocation;
    List<LocationQuantityEntity> locationQuantities = new ArrayList<LocationQuantityEntity>();
    private long classicNutriBarNuts;
    private long classicNutriBarFruits;
    private long premiumPowerBarNuts;
    private long premiumPowerBarFruits;
    private long totalClassicNutriBarNuts;
    private long totalClassicNutriBarFruits;
    private long totalPremiumPowerBarNuts;
    private long totalPremiumPowerBarFruits;
    private ProductQuantityPriceEntity currentPQP;
    private ProductQuantityPriceEntity currentPQP2;
    private ProductQuantityPriceEntity currentPQP3;
    private ProductQuantityPriceEntity currentPQP4;
    private Collection<ProductQuantityPriceEntity> pqp; //= new ArrayList<ProductQuantityPriceEntity>();
    private int leftToPick;
    private PickingOrderEntity pickingOrderEntity = null;
    
    public CompletedGoodsEntityController() {
//        createNewBomMaterialList();
    }
    
    public int getLeftToPick() {
        if (pickingOrderEntity != null) {
            System.out.println(pickingOrderEntity.getId() + "picking order id");
            this.leftToPick = pickingOrderEntity.getReservation().getQuantity();
            if (this.leftToPick == 0) {
                pickingOrderEntity.setArchived(true);
                this.getPickingOrderEntityController().getEjbFacade().edit(pickingOrderEntity);
            }
        } else {
            leftToPick = 0;
        }
        return leftToPick;
    }
//    public int getLeftToPick() {
//        this.setLeftToPick(0);
//        List<Object> reservations = new ArrayList(this.getSalesOrderEntityController().getSelected().getReservations());
//        System.out.println("SalesOrderId" + this.getSalesOrderEntityController().getSelected().getId());
//
//        if (reservations.size() > 0) {
//            for (Object obj : reservations) {
//                ReservationEntity reservation = (ReservationEntity) obj;
//                //System.out.println(reservation.getId());
//                if (reservation != null) {
//                    if (reservation.isArchived() == false) {
//                        leftToPick = leftToPick + reservation.getQuantity();
//                    }
//                }
//            }
//        }
////        
////        List<PlannedReserveEntity> plannedReserves = new ArrayList(this.getSalesOrderEntityController().getSelected().getPlannedReservation());
////        if (plannedReserves.size() > 0) {
////            for (Object obj : reservations) {
////                PlannedReserveEntity plannedReserve = (PlannedReserveEntity) obj;
////                if (plannedReserve != null) {
////                    if (plannedReserve.isArchived() == false) {
////                        leftToPick = leftToPick + plannedReserve.getQuantity();
////                    }
////                }
////            }
////        }
//
//        return leftToPick;
//    }

    public PickingOrderEntity getPickingOrderEntity() {
        return pickingOrderEntity;
    }
    
    public void setPickingOrderEntity(PickingOrderEntity pickingOrderEntity) {
        this.pickingOrderEntity = pickingOrderEntity;
    }
    
    public DualListModel<String> getRmsPickList() {
        
        List<RawMaterialEntity> allRMEntityList = new ArrayList<RawMaterialEntity>();
        
        allRMs.clear();
        allRMEntityList = materialFacade.findAll();
        
        for (int i = 0; i < allRMEntityList.size(); i++) {
            
            allRMs.add(allRMEntityList.get(i).getProductName());
            
        }
        
        rmsPickList = new DualListModel<String>(allRMs, choosenRMs);
        
        return rmsPickList;
        
    }
//for picklist
    private List<String> allRMs = new ArrayList<String>();
    private List<String> choosenRMs = new ArrayList<String>();
    private DualListModel<String> rmsPickList;
    
    public List<String> getAllRMs() {
        return allRMs;
    }
    
    public void setAllRMs(List<String> allRMs) {
        this.allRMs = allRMs;
    }
    
    public List<String> getChoosenRMs() {
        return rmsPickList.getTarget();
    }
    
    public void setChoosenRMs(List<String> choosenRMs) {
        this.choosenRMs = choosenRMs;
    }
    
    public void setRmsPickList(DualListModel<String> rmsPickList) {
        this.rmsPickList = rmsPickList;
    }
    
    public void setCompletedGoodsList(ArrayList<CompletedGoodsEntity> list) {
        completedGoodsList = list;
    }
    
    public ArrayList<CompletedGoodsEntity> getCompletedGoodsList() {
        completedGoodsList = new ArrayList<CompletedGoodsEntity>(getFacade().findAll());
        return completedGoodsList;
    }
    
    public void setBomMaterialList(ArrayList<BomRawMaterialWeightEntity> list) {
        bomMaterialList = list;
    }
    
    public void validateMaterialName(FacesContext context, UIComponent validate, Object value) {
        
        String materialName = (String) value;
        if (ejbFacade.checkUserNameExist(materialName, ejbFacade.findAll())) {
            FacesMessage message = new FacesMessage();
            message.setDetail("Product Name exists");
            message.setSummary("Product Name exists");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message);
        }
    }
    
    public void updateBOM() {
        choosenRMs = getChoosenRMs();
        List<String> choosenRMs = getChoosenRMs();
        bomMaterialList = new ArrayList<BomRawMaterialWeightEntity>();
        
        for (String rm : choosenRMs) {
            BomRawMaterialWeightEntity b = new BomRawMaterialWeightEntity();
            b.setRawMaterial(materialFacade.findRawMaterial(rm));
            b.setBomWeight(0);
            
            bomMaterialList.add(b);
        }
    }
    
    public ArrayList<BomRawMaterialWeightEntity> getBomMaterialList() {
//              List<String> choosenRMs = getChoosenRMs();
//             bomMaterialList = new ArrayList<BomRawMaterialWeightEntity>();
//             
//             for (String rm : choosenRMs) {
//            BomRawMaterialWeightEntity b = new BomRawMaterialWeightEntity();
//            b.setRawMaterial( materialFacade.findRawMaterial(rm));
//            b.setBomWeight(0);
//            
//            bomMaterialList.add(b);
//             }
        
        
        return bomMaterialList;
    }

//    public ArrayList<BomRawMaterialWeightEntity> getBomMaterialList(){
//        return bomMaterialList;
//    }
    public void setLeftToPick(int leftToPick) {
        this.leftToPick = leftToPick;
    }
    
    public void validatePickAmount(FacesContext context, UIComponent validate, Object value) {
        
        int pickAmt = (Integer) value;
        System.out.println("LocationQuantityHere" + this.getLocationQuantityEntityController().getSelected().getQuantity());
        System.out.println("LocationQuantityHere" + this.getLocationQuantityEntityController().getSelected().getQuantity());
        if (pickAmt > this.getLeftToPick() || pickAmt > this.getLocationQuantityEntityController().getSelected().getQuantity()) {
            FacesMessage message = new FacesMessage();
            message.setDetail("Amount too much!");
            message.setSummary("Amount too much!");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message);
        }
    }
    
    public OutboundCompletedGoodsEntityController getOutboundCompletedGoodsEntityController() {
        return outboundCompletedGoodsEntityController;
    }
    
    public void setOutboundCompletedGoodsEntityController(OutboundCompletedGoodsEntityController outboundCompletedGoodsEntityController) {
        this.outboundCompletedGoodsEntityController = outboundCompletedGoodsEntityController;
    }
    
    public String viewThisGood(CompletedGoodsEntity good) {
        current = good;
        
        return "/entities/completedGoodsEntity/View?faces-redirect=true";
        
    }
    
    public String onFlowProcess(FlowEvent event) {        
        
        logger.info("Current wizard step:" + event.getOldStep());        
        logger.info("Next step:" + event.getNewStep());        
        
        
        return event.getNewStep();        
        
    }    
    
    public void fulfilPickingOrder() {
        try {
            System.out.println(getLocationQuantityEntityController().getSelected().getQuantity());
            LocationQuantityEntity lqe = this.getLocationQuantityEntityController().getSelected();
            System.out.println("toremovecase " + getLocationQuantityEntityController().getToRemoveCase());
            lqe.setQuantity(lqe.getQuantity() - getLocationQuantityEntityController().getToRemoveCase());
            CompletedGoodsLocationEntity CGLocationEntity = (CompletedGoodsLocationEntity) lqe.getLocation();
            CGLocationEntity.setUsageCase(CGLocationEntity.getUsageCase() - getLocationQuantityEntityController().getToRemoveCase());
            this.getCompletedGoodsLocationEntityController().getFacade().edit(CGLocationEntity);
            if (lqe.getQuantity() == 0) {
                lqe.setArchived(true);
            }
            System.out.println("SalesOrderID" + this.getSalesOrderEntityController().getSelected().getId());

            //System.out.println("SOReservationID"+SOreservations.get(0).getId());
            //System.out.println(this.getSalesOrderEntityController().getSelected().getReservations().iterator());
            List<ReservationEntity> reservations = new ArrayList(this.getSalesOrderEntityController().getSelected().getReservations());

//        System.out.println("Reservations size"+reservations.get(1).getId()); 
            for (ReservationEntity reservation : reservations) {
                if (reservation.isArchived() == false) {
                    if (reservation.getPickingOrder().equals(this.getPickingOrderEntityController().getSelected())) {
                        reservation.setQuantity(reservation.getQuantity() - getLocationQuantityEntityController().getToRemoveCase());
                        getReservationEntityController().getEjbFacade().edit(reservation);
                    }
                }
            }
            
            getLocationQuantityEntityController().getEjbFacade().edit(lqe);
            
            OutboundCompletedGoodsEntity outboundCG = new OutboundCompletedGoodsEntity();
            outboundCG.setBatch(lqe.getInventory().getBatch());
            outboundCG.setType("Picked");
            outboundCG.setQuantityRemoved(getLocationQuantityEntityController().getToRemoveCase());
            this.getOutboundCompletedGoodsEntityController().getEjbFacade().create(outboundCG);
            
            this.getLocationQuantityEntityController().setToRemoveCase(0);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    public ReservationEntityController getReservationEntityController() {
        return reservationEntityController;
    }
    
    public void setReservationEntityController(ReservationEntityController reservationEntityController) {
        this.reservationEntityController = reservationEntityController;
    }
    
    public PickingOrderEntityController getPickingOrderEntityController() {
        return pickingOrderEntityController;
    }
    
    public void setPickingOrderEntityController(PickingOrderEntityController pickingOrderEntityController) {
        this.pickingOrderEntityController = pickingOrderEntityController;
    }
    
    public SalesOrderEntityController getSalesOrderEntityController() {
        return salesOrderEntityController;
    }
    
    public void setSalesOrderEntityController(SalesOrderEntityController salesOrderEntityController) {
        this.salesOrderEntityController = salesOrderEntityController;
    }
    
    public DisposalEntityController getDisposalEntityController() {
        return disposalEntityController;
    }
    
    public void setDisposalEntityController(DisposalEntityController disposalEntityController) {
        this.disposalEntityController = disposalEntityController;
    }
    
    public BatchEntityController getBatchEntityController() {
        return batchEntityController;
    }
    
    public void setBatchEntityController(BatchEntityController batchEntityController) {
        this.batchEntityController = batchEntityController;
    }
    
    public InventoryEntityController getInventoryEntityController() {
        return inventoryEntityController;
    }
    
    public void setInventoryEntityController(InventoryEntityController inventoryEntityController) {
        this.inventoryEntityController = inventoryEntityController;
    }
    
    public LocationQuantityEntityController getLocationQuantityEntityController() {
        return locationQuantityEntityController;
    }
    
    public void setLocationQuantityEntityController(LocationQuantityEntityController locationQuantityEntityController) {
        this.locationQuantityEntityController = locationQuantityEntityController;
    }
    
    public BatchEntity getBatchToRemove() {
        return batchToRemove;
    }
    private LocationQuantityEntity locationToRemove;
    
    public LocationQuantityEntity getLocationToRemove() {
        return locationToRemove;
    }
    
    public void setLocationToRemove(LocationQuantityEntity locationToRemove) {
        System.out.println("insetbatchtoremove");
        this.batchToRemove = locationToRemove.getInventory().getBatch();
        
        OutboundCompletedGoodsEntity outboundCG = new OutboundCompletedGoodsEntity();
        outboundCG.setType("Expired");
        outboundCG.setBatch(batchToRemove);
        
        List<LocationQuantityEntity> locationToQuantityList = new ArrayList<LocationQuantityEntity>(batchToRemove.getInventory().getLocationToQuantity());
        for (int i = 0; i < locationToQuantityList.size(); i++) {
            LocationQuantityEntity locationQuantityEntity = locationToQuantityList.get(i);
            System.out.println(locationQuantityEntity.getId());
            System.out.println(viewLocation.getId());
            if (locationQuantityEntity.getLocation().equals(viewLocation)) {
                locationQuantityEntity.setArchived(true);
                
                locationQuantityEntity.getInventory().setCurrentQuantity(locationQuantityEntity.getInventory().getCurrentQuantity() - locationQuantityEntity.getQuantity());
                viewLocation.setUsageCase(viewLocation.getUsageCase() - locationQuantityEntity.getQuantity());
                this.batchToRemove.getDisposal().setQuantity(this.batchToRemove.getDisposal().getQuantity() + locationQuantityEntity.getQuantity());
                
                outboundCG.setQuantityRemoved(locationQuantityEntity.getQuantity());
                
                getCompletedGoodsLocationEntityController().getFacade().edit(viewLocation);
                getBatchEntityController().getEjbFacade().edit(locationQuantityEntity.getInventory().getBatch());
                getInventoryEntityController().getEjbFacade().edit(locationQuantityEntity.getInventory());
                getLocationQuantityEntityController().getEjbFacade().edit(locationQuantityEntity);
                getDisposalEntityController().getEjbFacade().edit(this.batchToRemove.getDisposal());
            }
        }
        this.getOutboundCompletedGoodsEntityController().getEjbFacade().create(outboundCG);
        
        
        
        FacesContext context = FacesContext.getCurrentInstance();
        String viewId = context.getViewRoot().getViewId();
        ViewHandler handler = context.getApplication().getViewHandler();
        UIViewRoot root = handler.createView(context, viewId);
        root.setViewId(viewId);
        context.setViewRoot(root);
    }
    
    public void setBatchToRemove(BatchEntity batchToRemove) {
        this.batchToRemove = batchToRemove;
    }
    private DataModel expiringLocationToQuantities;
    
    public DataModel getExpiringLocationToQuantities() {
        return expiringLocationToQuantities;
    }
    
    public void setExpiringLocationToQuantities(DataModel expiringLocationToQuantities) {
        this.expiringLocationToQuantities = expiringLocationToQuantities;
    }
    
    public DataModel getExpiringBatchesInLocation() {
        System.out.println("getbatchesinlocation");
        return expiringBatchesInLocation;
    }
    
    public void setExpiringBatchesInLocation(DataModel expiringBatchesInLocation) {
        this.expiringBatchesInLocation = expiringBatchesInLocation;
    }
    
    public void resetQuantities() {
        setClassicNutriBarNuts(0);
        setClassicNutriBarFruits(0);
        setPremiumPowerBarFruits(0);
        setPremiumPowerBarNuts(0);
        setTotalClassicNutriBarNuts(0);
        setTotalClassicNutriBarFruits(0);
        setTotalPremiumPowerBarFruits(0);
        setTotalPremiumPowerBarNuts(0);
    }

//    public void checkInventory() {
//        System.out.println("in check inventory");
//        resetQuantities();
//        System.out.println("in check inventory1");
//        List<ProductQuantityPriceEntity> pqpList = new ArrayList<ProductQuantityPriceEntity>(getPqp());
//        System.out.println("in check inventory2");
//        for (ProductQuantityPriceEntity pqp : pqpList) {
//            System.out.println("in check inventory3");
//            String productName = pqp.getProduct().getProductName();
//            if (productName.equals("Classic Nutri Bar (Nuts)")) {
//                setClassicNutriBarNuts(pqp.getQuantity());
//            }
//            if (productName.equals("Classic Nutri Bar (Fruits)")) {
//                setClassicNutriBarFruits(pqp.getQuantity());
//            }
//            if (productName.equals("Premium Power Bar (Chocolate Nuts)")) {
//                setPremiumPowerBarNuts(pqp.getQuantity());
//            }
//            if (productName.equals("Premium Power Bar (Redcurrant Fruits)")) {
//                setPremiumPowerBarFruits(pqp.getQuantity());
//            }
//        }
//    }
    public Collection<ProductQuantityPriceEntity> getPqp() {
        return pqp;
    }
    
    public void setPqp(Collection<ProductQuantityPriceEntity> pqps) {
        this.pqp = pqps;
        
        resetQuantities();
        System.out.println("in check inventory1");
        List<ProductQuantityPriceEntity> pqpList = new ArrayList<ProductQuantityPriceEntity>(getPqp());
        System.out.println("in check inventory2");
        for (ProductQuantityPriceEntity pqp : pqpList) {
            System.out.println("in check inventory3");
            String productName = pqp.getProduct().getProductName();
            if (productName.equals("Classic Nutri Bar (Nuts)")) {
                setClassicNutriBarNuts(pqp.getQuantity());
            }
            if (productName.equals("Classic Nutri Bar (Fruits)")) {
                setClassicNutriBarFruits(pqp.getQuantity());
            }
            if (productName.equals("Premium Power Bar (Chocolate Nuts)")) {
                setPremiumPowerBarNuts(pqp.getQuantity());
            }
            if (productName.equals("Premium Power Bar (Redcurrant Fruits)")) {
                setPremiumPowerBarFruits(pqp.getQuantity());
            }
        }
        
    }
    
    public CompletedGoodsLocationEntity getViewLocation() {
        if (viewLocation == null) {
            viewLocation = new CompletedGoodsLocationEntity();
        }
        return viewLocation;
    }
//
//    public String getCgLocationView() {
//        locationQuantities = this.getFacade().findAllCGInLocation(viewLocation.getId());
//        for (LocationQuantityEntity locationQuantity : locationQuantities) {
//            if (locationQuantity.isArchived() == false) {
//                String productName = locationQuantity.getInventory().getBatch().getProduct().getProductName();
//
//                if (productName.equals("Classic Nutri Bar (Nuts)")) {
//                    classicNutriBarNuts = classicNutriBarNuts + locationQuantity.getInventory().getCurrentQuantity();
//                }
//                if (productName.equals("Classic Nutri Bar (Fruits)")) {
//                    classicNutriBarFruits = classicNutriBarFruits + locationQuantity.getInventory().getCurrentQuantity();
//                }
//                if (productName.equals("Premium Power Bar (Chocolate Nuts)")) {
//                    premiumPowerBarNuts = premiumPowerBarNuts + locationQuantity.getInventory().getCurrentQuantity();
//                }
//                if (productName.equals("Premium Power Bar (Redcurrant Fruits)")) {
//                    premiumPowerBarFruits = premiumPowerBarFruits + locationQuantity.getInventory().getCurrentQuantity();
//                }
//            }
//
//        }
//        return "cgLocationDialog.show()";
//    }

    public void setViewLocation(CompletedGoodsLocationEntity viewLocation) {
        this.viewLocation = viewLocation;
        
        setClassicNutriBarNuts(0);
        setClassicNutriBarFruits(0);
        setPremiumPowerBarFruits(0);
        setPremiumPowerBarNuts(0);
        
        locationQuantities = this.getFacade().findAllCGInLocation(viewLocation.getId());
        for (LocationQuantityEntity locationQuantity : locationQuantities) {
            if (locationQuantity.getLocation().getType().equals("CG")) {
                String productName = locationQuantity.getInventory().getBatch().getProduct().getProductName();
                
                if (productName.equals("Classic Nutri Bar (Nuts)")) {
                    setClassicNutriBarNuts(getClassicNutriBarNuts() + locationQuantity.getQuantity());
                } else if (productName.equals("Classic Nutri Bar (Fruits)")) {
                    setClassicNutriBarFruits(getClassicNutriBarFruits() + locationQuantity.getQuantity());
                } else if (productName.equals("Premium Power Bar (Chocolate Nuts)")) {
                    setPremiumPowerBarFruits(getPremiumPowerBarNuts() + locationQuantity.getQuantity());
                } else if (productName.equals("Premium Power Bar (Redcurrant Fruits)")) {
                    setPremiumPowerBarFruits(getPremiumPowerBarFruits() + locationQuantity.getQuantity());
                }
            }
        }
    }
    
    public void setExpiringCGInLocation(CompletedGoodsLocationEntity viewLocation) {
        //expiringBatches=null;
        System.out.println("after click alert");
        this.viewLocation = viewLocation;
        
        Date currentDate = new Date();
        SimpleDateFormat sdfDate = new SimpleDateFormat("dd/MM/yyyy");
        sdfDate.format(currentDate);
        Calendar c = Calendar.getInstance();
        c.setTime(currentDate);
        c.add(Calendar.DATE, 30);  // number of days to add

        List<BatchEntity> expiringBatches = new ArrayList<BatchEntity>();
        List<LocationQuantityEntity> expiringLQEs = new ArrayList<LocationQuantityEntity>();
        System.out.println(viewLocation.getId());
        locationQuantities = this.getFacade().findAllCGInLocation(viewLocation.getId());
        for (LocationQuantityEntity locationQuantity : locationQuantities) {
            if (locationQuantity.getLocation().getType().equals("CG")) {
                if (locationQuantity.getInventory().getBatch().getExpiryDate().before(c.getTime()) && !expiringBatches.contains(locationQuantity.getInventory().getBatch())) {
                    if (locationQuantity.getLocation().equals(viewLocation) && !locationQuantity.getInventory().getBatch().isArchived()) {
                        expiringBatches.add(locationQuantity.getInventory().getBatch());
                        expiringLQEs.add(locationQuantity);
                    }
                }
            }
        }
        
        this.expiringLocationToQuantities = new ListDataModel(expiringLQEs);
        this.expiringBatchesInLocation = new ListDataModel(expiringBatches);
    }

//    public int expiringQuantityInLocation(){
//        
//        this.getExpiringLocationToQuantities();
//        
//    }
    public int getTotalCGUsage() {
        totalCGUsage = 0;
        List<CompletedGoodsLocationEntity> completedGoodsLocations = new ArrayList<CompletedGoodsLocationEntity>(getCompletedGoodsLocationEntityController().getFacade().findAllIncludeArchived());
        
        for (int i = 0; i < completedGoodsLocations.size(); i++) {
            totalCGUsage = totalCGUsage + completedGoodsLocations.get(i).getUsageCase();
        }
        return totalCGUsage;
    }
    
    public void setTotalCGUsage(int totalCGUsage) {
        this.totalCGUsage = totalCGUsage;
    }
    
    public int getTotalCGCapacity() {
        totalCGCapacity = 0;
        List<CompletedGoodsLocationEntity> completedGoodsLocations = new ArrayList<CompletedGoodsLocationEntity>(getCompletedGoodsLocationEntityController().getFacade().findAllIncludeArchived());
        
        for (int i = 0; i < completedGoodsLocations.size(); i++) {
            totalCGCapacity = totalCGCapacity + completedGoodsLocations.get(i).getCapacityCase();
        }
        return totalCGCapacity;
    }
    
    public void setTotalCGCapacity(int totalCGCapacity) {
        this.totalCGCapacity = totalCGCapacity;
    }
    
    public CompletedGoodsEntityFacade getEjbFacade() {
        return ejbFacade;
    }
    
    public void setEjbFacade(CompletedGoodsEntityFacade ejbFacade) {
        this.ejbFacade = ejbFacade;
    }
    
    public CompletedGoodsLocationEntityController getCompletedGoodsLocationEntityController() {
        return completedGoodsLocationEntityController;
    }
    
    public void setCompletedGoodsLocationEntityController(CompletedGoodsLocationEntityController completedGoodsLocationEntityController) {
        this.completedGoodsLocationEntityController = completedGoodsLocationEntityController;
    }
    
    public CompletedGoodsEntity getSelected() {
        if (current == null) {
            current = new CompletedGoodsEntity();
            selectedItemIndex = -1;
        }
        return current;
    }
    
    private CompletedGoodsEntityFacade getFacade() {
        return ejbFacade;
    }
    
    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }
                
                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }
    
    public String prepareList() {
        recreateModel();
        
        return "/entities/completedGoodsEntity/List?faces-redirect=true";
    }
    
    public String prepareView() {
        current = (CompletedGoodsEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }
    
    public String prepareCreate() {
        current = new CompletedGoodsEntity();
        
        return "/entities/completedGoodsEntity/Create?faces-redirect=true";
    }
    
    public String create() {
        try {
            getFacade().createCompletedGood(current, bomMaterialList);
            
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CompletedGoodsEntityCreated"));
            return "/entities/completedGoodsEntity/List?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }
    
    public String prepareEdit() {
        current = (CompletedGoodsEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }
    
    public String prepareEdit(CompletedGoodsEntity good) {
        current = good;
        
        return "Edit";
    }
    
    public String update() {
        try {
            getFacade().updateGood(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CompletedGoodsEntityUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }
    
    public String destroy() {
        current = (CompletedGoodsEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }
    
    public String destroy(CompletedGoodsEntity good) {
        current = good;
        
        getFacade().delete(good);
        recreateModel();
        return "List";
    }
    
    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }
    
    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CompletedGoodsEntityDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }
    
    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }
    
    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }
    
    private void recreateModel() {
        items = null;
        current = null;
        choosenRMs = new ArrayList<String>();
        bomMaterialList = new ArrayList<BomRawMaterialWeightEntity>();
    }
    
    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }
    
    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }
    
    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }
    
    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }
    
    @FacesConverter(forClass = CompletedGoodsEntity.class)
    public static class CompletedGoodsEntityControllerConverter implements Converter {
        
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CompletedGoodsEntityController controller = (CompletedGoodsEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "completedGoodsEntityController");
            return controller.ejbFacade.find(getKey(value));
        }
        
        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }
        
        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }
        
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof CompletedGoodsEntity) {
                CompletedGoodsEntity o = (CompletedGoodsEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + CompletedGoodsEntityController.class.getName());
            }
        }
    }
    
    public long getClassicNutriBarFruits() {
        return classicNutriBarFruits;
    }
    
    public void setClassicNutriBarFruits(long classicNutriBarFruits) {
        this.classicNutriBarFruits = classicNutriBarFruits;
    }
    
    public long getClassicNutriBarNuts() {
        return classicNutriBarNuts;
    }
    
    public void setClassicNutriBarNuts(long classicNutriBarNuts) {
        this.classicNutriBarNuts = classicNutriBarNuts;
    }
    
    public long getPremiumPowerBarFruits() {
        return premiumPowerBarFruits;
    }
    
    public void setPremiumPowerBarFruits(long premiumPowerBarFruits) {
        this.premiumPowerBarFruits = premiumPowerBarFruits;
    }
    
    public long getPremiumPowerBarNuts() {
        return premiumPowerBarNuts;
    }
    
    public void setPremiumPowerBarNuts(long premiumPowerBarNuts) {
        this.premiumPowerBarNuts = premiumPowerBarNuts;
    }
    
    public long getTotalClassicNutriBarFruits() {
        setTotalClassicNutriBarFruits(0);
        locationQuantities = this.getFacade().findAllCG();
        for (LocationQuantityEntity locationQuantity : locationQuantities) {
            String productName = locationQuantity.getInventory().getBatch().getProduct().getProductName();
            if (productName.equals("Classic Nutri Bar (Fruits)")) {
                if (locationQuantity.isArchived() == false) {
                    setTotalClassicNutriBarFruits(totalClassicNutriBarFruits + locationQuantity.getQuantity());
                }
            }
        }
        List<SalesOrderEntity> allSalesOrders = getSalesOrderEntityController().getEjbFacade().findAll();
        for (SalesOrderEntity salesOrder : allSalesOrders) {
            List<ReservationEntity> reservations = new ArrayList<ReservationEntity>(salesOrder.getReservations());
            for (ReservationEntity reservation : reservations) {
                if (reservation.getProduct().getProductName().equals("Classic Nutri Bar (Fruits)")) {
                    if (reservation.isArchived() == false) {
                        totalClassicNutriBarFruits = totalClassicNutriBarFruits - reservation.getQuantity();
                    }
                }
            }
        }
        return totalClassicNutriBarFruits;
    }
    
    public void setTotalClassicNutriBarFruits(long totalClassicNutriBarFruits) {
        this.totalClassicNutriBarFruits = totalClassicNutriBarFruits;
    }
    private int totalReservedClassicNutriBarNuts;
    
    public int getTotalReservedClassicNutriBarNuts() {
        totalReservedClassicNutriBarNuts = 0;
        List<SalesOrderEntity> allSalesOrders = getSalesOrderEntityController().getEjbFacade().findAll();
        for (SalesOrderEntity salesOrder : allSalesOrders) {
            List<ReservationEntity> reservations = new ArrayList<ReservationEntity>(salesOrder.getReservations());
            for (ReservationEntity reservation : reservations) {
                if (reservation.getProduct().getProductName().equals("Classic Nutri Bar (Nuts)")) {
                    if (reservation.isArchived() == false) {
                        totalReservedClassicNutriBarNuts = totalReservedClassicNutriBarNuts + reservation.getQuantity();
                    }
                }
            }
        }
        return totalReservedClassicNutriBarNuts;
    }
    private int totalReservedClassicNutriBarFruits;
    
    public int getTotalReservedClassicNutriBarFruits() {
        totalReservedClassicNutriBarFruits = 0;
        List<SalesOrderEntity> allSalesOrders = getSalesOrderEntityController().getEjbFacade().findAll();
        for (SalesOrderEntity salesOrder : allSalesOrders) {
            List<ReservationEntity> reservations = new ArrayList<ReservationEntity>(salesOrder.getReservations());
            for (ReservationEntity reservation : reservations) {
                if (reservation.getProduct().getProductName().equals("Classic Nutri Bar (Fruits)")) {
                    if (reservation.isArchived() == false) {
                        totalReservedClassicNutriBarFruits = totalReservedClassicNutriBarFruits + reservation.getQuantity();
                    }
                }
            }
        }
        return totalReservedClassicNutriBarFruits;
    }
    private int totalReservedPremiumPowerBarFruits;
    
    public int getTotalReservedPremiumPowerBarFruits() {
        totalReservedPremiumPowerBarFruits = 0;
        List<SalesOrderEntity> allSalesOrders = getSalesOrderEntityController().getEjbFacade().findAll();
        for (SalesOrderEntity salesOrder : allSalesOrders) {
            List<ReservationEntity> reservations = new ArrayList<ReservationEntity>(salesOrder.getReservations());
            for (ReservationEntity reservation : reservations) {
                if (reservation.getProduct().getProductName().equals("Premium Power Bar (Redcurrant Fruits)")) {
                    if (reservation.isArchived() == false) {
                        totalReservedPremiumPowerBarFruits = totalReservedPremiumPowerBarFruits + reservation.getQuantity();
                    }
                }
            }
        }
        return totalReservedPremiumPowerBarFruits;
    }
    private int totalReservedPremiumPowerBarNuts;
    
    public int getTotalReservedPremiumPowerBarNuts() {
        totalReservedPremiumPowerBarNuts = 0;
        List<SalesOrderEntity> allSalesOrders = getSalesOrderEntityController().getEjbFacade().findAll();
        for (SalesOrderEntity salesOrder : allSalesOrders) {
            List<ReservationEntity> reservations = new ArrayList<ReservationEntity>(salesOrder.getReservations());
            for (ReservationEntity reservation : reservations) {
                if (reservation.getProduct().getProductName().equals("Premium Power Bar (Chocolate Nuts)")) {
                    if (reservation.isArchived() == false) {
                        totalReservedPremiumPowerBarNuts = totalReservedPremiumPowerBarNuts + reservation.getQuantity();
                    }
                }
            }
        }
        return totalReservedPremiumPowerBarNuts;
    }
    
    public long getTotalClassicNutriBarNuts() {
        setTotalClassicNutriBarNuts(0);
        
        locationQuantities = this.getFacade().findAllCG();
        for (LocationQuantityEntity locationQuantity : locationQuantities) {
            String productName = locationQuantity.getInventory().getBatch().getProduct().getProductName();
            if (productName.equals("Classic Nutri Bar (Nuts)")) {
                if (locationQuantity.isArchived() == false) {
                    setTotalClassicNutriBarNuts(totalClassicNutriBarNuts + locationQuantity.getQuantity());
                }
            }
        }
        
        List<SalesOrderEntity> allSalesOrders = getSalesOrderEntityController().getEjbFacade().findAll();
        for (SalesOrderEntity salesOrder : allSalesOrders) {
            List<ReservationEntity> reservations = new ArrayList<ReservationEntity>(salesOrder.getReservations());
            for (ReservationEntity reservation : reservations) {
                if (reservation.getProduct().getProductName().equals("Classic Nutri Bar (Nuts)")) {
                    if (reservation.isArchived() == false) {
                        totalClassicNutriBarNuts = totalClassicNutriBarNuts - reservation.getQuantity();
                    }
                }
            }
        }
        return totalClassicNutriBarNuts;
    }
    
    public void setTotalClassicNutriBarNuts(long totalClassicNutriBarNuts) {
        this.totalClassicNutriBarNuts = totalClassicNutriBarNuts;
    }
    
    public long getTotalPremiumPowerBarFruits() {
        setTotalPremiumPowerBarFruits(0);
        locationQuantities = this.getFacade().findAllCG();
        for (LocationQuantityEntity locationQuantity : locationQuantities) {
            String productName = locationQuantity.getInventory().getBatch().getProduct().getProductName();
            
            if (productName.equals("Premium Power Bar (Redcurrant Fruits)")) {
                if (locationQuantity.isArchived() == false) {
                    setTotalPremiumPowerBarFruits(totalPremiumPowerBarFruits + locationQuantity.getQuantity());
                }
            }
        }
        List<SalesOrderEntity> allSalesOrders = getSalesOrderEntityController().getEjbFacade().findAll();
        for (SalesOrderEntity salesOrder : allSalesOrders) {
            List<ReservationEntity> reservations = new ArrayList<ReservationEntity>(salesOrder.getReservations());
            for (ReservationEntity reservation : reservations) {
                System.out.println("Number of reservations:" + reservations.size());
                if (reservation.getProduct().getProductName().equals("Premium Power Bar (Redcurrant Fruits)")) {
                    System.out.println(reservation.getProduct().getProductName() + "Product name");
                    if (reservation.isArchived() == false) {
                        System.out.println("reservation quantity:" + reservation.getQuantity());
                        totalPremiumPowerBarFruits = totalPremiumPowerBarFruits - reservation.getQuantity();
                    }
                }
            }
        }
        return totalPremiumPowerBarFruits;
    }
    
    public void setTotalPremiumPowerBarFruits(long totalPremiumPowerBarFruits) {
        this.totalPremiumPowerBarFruits = totalPremiumPowerBarFruits;
    }
    
    public long getTotalPremiumPowerBarNuts() {
        setTotalPremiumPowerBarNuts(0);
        locationQuantities = this.getFacade().findAllCG();
        for (LocationQuantityEntity locationQuantity : locationQuantities) {
            String productName = locationQuantity.getInventory().getBatch().getProduct().getProductName();
            
            if (productName.equals("Premium Power Bar (Chocolate Nuts)")) {
                if (locationQuantity.isArchived() == false) {
                    setTotalPremiumPowerBarNuts(totalPremiumPowerBarNuts + locationQuantity.getQuantity());
                }
            }
        }
        List<SalesOrderEntity> allSalesOrders = getSalesOrderEntityController().getEjbFacade().findAll();
        for (SalesOrderEntity salesOrder : allSalesOrders) {
            List<ReservationEntity> reservations = new ArrayList<ReservationEntity>(salesOrder.getReservations());
            for (ReservationEntity reservation : reservations) {
                if (reservation.getProduct().getProductName().equals("Premium Power Bar (Chocolate Nuts)")) {
                    if (reservation.isArchived() == false) {
                        totalPremiumPowerBarNuts = totalPremiumPowerBarNuts - reservation.getQuantity();
                    }
                }
            }
        }
        return totalPremiumPowerBarNuts;
    }
    
    public void setTotalPremiumPowerBarNuts(long totalPremiumPowerBarNuts) {
        
        this.totalPremiumPowerBarNuts = totalPremiumPowerBarNuts;
    }
    
    public ProductQuantityPriceEntity getCurrentPQP() {
        return currentPQP;
    }
    
    public void setCurrentPQP(ProductQuantityPriceEntity currentPQP) {
        this.currentPQP = currentPQP;
    }
    
    public ProductQuantityPriceEntity getCurrentPQP2() {
        return currentPQP2;
    }
    
    public void setCurrentPQP2(ProductQuantityPriceEntity currentPQP2) {
        this.currentPQP2 = currentPQP2;
    }
    
    public ProductQuantityPriceEntity getCurrentPQP3() {
        return currentPQP3;
    }
    
    public void setCurrentPQP3(ProductQuantityPriceEntity currentPQP3) {
        this.currentPQP3 = currentPQP3;
    }
    
    public ProductQuantityPriceEntity getCurrentPQP4() {
        return currentPQP4;
    }
    
    public void setCurrentPQP4(ProductQuantityPriceEntity currentPQP4) {
        this.currentPQP4 = currentPQP4;
    }
}
